from __future__ import annotations

import time
# from telnetlib import EC

import pages
from selenium.webdriver.support.wait import WebDriverWait


class LoginPage:
    def __init__(self):
        pass

    # 封装的一些方法
    def login(self,driver,login_url):
        driver.get(login_url)
        driver.maximize_window()
        time.sleep(2)
#     # def click_change_btn(self,driver):
#     #     webcontrol=WebControl()
#     #     webcontrol.Click(driver,"//button[contains(@class,'text-fg-01-light')]")
#     #     time.sleep(2)
#     # def screen_shoot_element1(self,driver,picname):
#     #     webcontrol = WebControl()
#     #     webcontrol.screenshot_ocr(driver, '(//span[@class="flex-1"])[1]', picname)
#     # def screen_shoot_content1(self,driver,picname):
#     #     webcontrol = WebControl()
#     #     webcontrol.screenshot_ocr(driver, '//h1[contains(@class,"mt-4 whitespace-pre-line")]', picname)
#     #

from typing import TypedDict, NotRequired

from selenium.common import TimeoutException
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import logging
from pathlib import Path
from datetime import datetime
from timeit import default_timer
import sys


# 类型定义
class Locator(TypedDict):
    by: str
    value: str


class ExpectedTexts(TypedDict):
    text_main: str
    text_middle: str
    head_left_btn1: str
    head_left_btn2: str
    head_left_btn3: str
    head_left_btn4: str
    head_right_btn1: str
    head_right_btn2: str
    start_btn: NotRequired[str]  # Python 3.11+ 特性


# 元素定位配置（使用类型注解）
TEXT_ELEMENTS: dict[str, Locator] = {
    'text_main': {'by': By.XPATH, 'value': '//h1[contains(@class,"mt-4 whitespace-pre-line")]'},
    'text_middle': {'by': By.XPATH, 'value': '//span[contains(@class,"text-pretty text-sm leading-5")]'},
    # 其他元素配置...
}

EXPECTED_TEXTS: dict[int, ExpectedTexts] = {
    1: {
    #     'text_main': "AI Mind Map Summarizer",
    #     'text_middle': "Summarize YouTube...",
    #     # 其他字段...
    # },
    # # 其他语言配置...


        'text_main': "AI Mind Map Summarizer",
        'text_middle': "Summarize YouTube, PDFs/Docs, URLs, Long Emails,Meeting Recordings into Mind Maps in seconds.Powered by GPT-4o, Claude 3.5, or other top LLMs.",
        'head_left_btn1': "Extension",
        'head_left_btn2':"Tools",
        'head_left_btn3':"Pricing",
        'head_left_btn4':"FAQ",
        'head_right_btn1':"Sign in",
        'head_right_btn2':"Start for free",
        'start_btn':"Start for free"
}}



class PageLanguage:
    """多语言测试页面操作类 (Python 3.12 优化版)"""

    def __init__(self, driver: WebDriver, screenshot_dir: str | Path = "screenshots") -> None:
        self.driver = driver
        self.screenshot_dir = Path(screenshot_dir)
        self._setup_directories()

        # 配置日志
        self.logger = logging.getLogger(self.__class__.__qualname__)
        self.logger.addHandler(logging.StreamHandler(sys.stdout))
        self.logger.setLevel(logging.INFO)

    def _setup_directories(self) -> None:
        """使用pathlib创建目录"""
        self.screenshot_dir.mkdir(exist_ok=True, parents=True)

    def _wait_for_element(self, locator: Locator, timeout: int = 10) -> str:
        """使用Python 3.12类型注解和结构化异常处理"""
        match locator:
            case {'by': by, 'value': value}:
                try:
                    element = WebDriverWait(self.driver, timeout).until(
                        EC.visibility_of_element_located((by, value))
                    )
                    return element.text.strip()
                except TimeoutException as e:
                    self.logger.error(f"元素加载超时: {locator}")
                    self._take_screenshot("element_timeout")
                    raise
                except Exception as e:
                    self.logger.error(f"元素定位异常: {e!r}", exc_info=True)
                    raise
            case _:
                raise ValueError(f"无效的定位器格式: {locator}")

    def _take_screenshot(self, prefix: str = "error") -> Path:
        """使用pathlib处理路径"""
        timestamp = datetime.now().isoformat(timespec="seconds").replace(":", "")
        filename = self.screenshot_dir / f"{prefix}_{timestamp}.png"

        try:
            self.driver.save_screenshot(str(filename))
            self.logger.info(f"截图已保存: {filename}")
            return filename
        except Exception as e:
            self.logger.error(f"截图失败: {e!r}")
            raise

    def verify_language(self, lang_id: int) -> dict[str, bool | str]:
        """主验证方法（返回详细结果）"""
        results: dict[str, bool | str] = {}
        start_time = default_timer()

        try:
            expected = EXPECTED_TEXTS[lang_id]
        except KeyError as e:
            self.logger.error(f"无效语言ID: {lang_id}")
            raise ValueError(f"未配置的语言ID: {lang_id}") from e

        self.logger.info(f"开始验证语言: {lang_id}")

        for element_name, expected_text in expected.items():
            try:
                if (locator := TEXT_ELEMENTS.get(element_name)) is None:
                    self.logger.warning(f"未定义的定位器: {element_name}")
                    continue

                actual_text = self._wait_for_element(locator)

                if actual_text != expected_text:
                    error_msg = (f"文本不匹配 - {element_name}\n"
                                 f"预期: {expected_text}\n"
                                 f"实际: {actual_text}")
                    results[element_name] = error_msg
                    self.logger.warning(error_msg)
                    self._take_screenshot(f"mismatch_{element_name}")
                else:
                    results[element_name] = True
                    self.logger.info(f"{element_name} 验证通过")

            except Exception as e:
                results[element_name] = f"验证异常: {e!r}"
                self.logger.error(f"{element_name} 验证失败", exc_info=True)

        elapsed = default_timer() - start_time
        self.logger.info(f"语言 {lang_id} 验证完成，耗时: {elapsed:.2f}s")
        return results

    # 其他页面操作方法...